# ================================================
# amboy.py - CheckNerds Labs.
# http://www.checknerds.com
# Backup all your items in CheckNerds.
# Original Author: CNBorn, http://cnborn.net, 2009
# 
#
# ================================================

'''
Usage: 
	Create your .checknerds file in your home directory(for example, /home/yourname/.checknerds)
	
	cp ./.checknerds.sample ~/.checknerds

	Edit ~/.checknerds, filled in with your CheckNerds ID and ApiKey
	
	Run command in terminal:

	python amboy.py

	there will be a export.csv file with all your information in CheckNerds.

'''

import httplib, urllib
import hashlib
import datetime
import csv
import getpass

import sys


from ConfigParser import ConfigParser
import os

filename = os.path.join(os.environ['HOME'], '.checknerds')

config = ConfigParser()
config.read([filename])

baseurl = config.get('base', 'base_url')

if baseurl == None:
	baseurl = "www.checknerds.com"

userid = config.get('base', 'userid')
if userid == None:
	userid = raw_input("Please input your CheckNerds userid:")

userkey = config.get('base', 'userkey')
if userkey == None:
	userkey = getpass.getpass("Please input your API key:")

appid = 74611
service392key = "0b34d532fca3bf5efd72be82f3edc8b1"

#Get Debug information

debug_mode = config.get('base', 'debug')
if debug_mode == '1':
		
	debug_baseurl = config.get('base', 'debug_base_url')
	if debug_baseurl != None:
		baseurl = debug_baseurl

	debug_userid = config.get('base', 'debug_userid')
	if debug_userid != None:
		userid = debug_userid

	debug_userkey = config.get('base', 'debug_userkey')
	if debug_userkey != None:
		userkey = debug_userkey

	debug_appid = config.get('base', 'debug_appid')
	if debug_appid != None:
		appid = debug_appid
	debug_service392key = config.get('base', 'debug_service392key')
	if debug_service392key != None:
		service392key = debug_service392key


sentkey = hashlib.sha256(service392key).hexdigest() 
sentuserkey = hashlib.sha256(userkey).hexdigest()

print "Connecting to server..."

beforedate = ''
edata_total = []
count = 1


conn = httplib.HTTPConnection(baseurl)
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}


while count!=0:

	params = urllib.urlencode({'apiappid':appid, 'servicekey':sentkey, 'apiuserid':userid, 'apikey':sentuserkey , 'userid':userid, 'beforedate':beforedate, 'maxitems':8})

	#print params
	conn.request("POST", "http://" + baseurl + "/service/item/", params, headers)
	response = conn.getresponse()
	data = response.read()
	conn.close()
	#print data

	#To Add Failure detection.

	try:
		edata = eval(data)
		count = len(edata)
		
		'''for a in edata:
			print a['date']
		print '------'
		'''


		if count >= 1:
			beforedate = edata[count-1]['date']
			
			#print "THIS IS IT:" + str(beforedate)
			#print count
			edata_total += edata

	except:
		if len(data) == 0:
			if len(edata_total) > 0:
				print "fetched " + str(len(edata_total)) + " items."
				print 'No more records, query finished.'
			else:				
				print "Something is wrong. "
		print data
		count = 0


# Write CSVs.

fieldnames = ('id', 'name', 'comment', 'date', 'done', 'expectdate', 'donedate', 'routine', 'public', 'tags')

writer = csv.DictWriter(open("export.csv", "wb"), fieldnames=fieldnames )


headers = {}
for n in fieldnames:
	headers[n] = n
writer.writerow(headers)

for eachItem in edata_total:
	record = {}
	# untested pseudocode for basestring-only case:
	for k, v in eachItem.iteritems():
		try:
			record[k]=v.encode('utf8')
		except:
			record[k] = v
	#print record

	writer.writerow(record)



